(function ($) {

    function ListView(target, options) {
        this.dbPath = G_Path.contextPath ? G_Path.contextPath : "";

        options = options || {};
        this.target = target;
        this.setting = options;
        this.fieldInfo = options.fieldInfo ? options.fieldInfo : [];
        if (options.url) {
            this.url = this.dbPath + this.setting.url;
        }
        this.viewUrl = options.viewUrl;
        this.editUrl = options.editUrl;
        this.deleteUrl = options.deleteUrl;
        this.searchUrl = options.searchUrl;
        this.searchName = options.searchName ? options.searchName : "请输入名称";
        this.toolsbarButtons = options.toolsbarButtons || {};
        this.toolsbarElement;
        this.containerElement;
        this.searchInputElement;
        this.type = {"img": 1, "data": 2};
        this.data = {};
        this.requestData = [];
        this.noHtml = "没有文档";
        this.start = 0;
        this.rowSize = 20;

        this.highlightResult = function () {
            this.style.color = "#00f";
            this.style.backgroundColor = "#ffffd1";
            this.toolsbarButtons = [];
            this.nowUserId = "";
        };
        this.unhighlightResult = function () {
            this.style.color = "#000";
            this.style.backgroundColor = "transparent";
        };
    }

    ListView.DEFAULTS = {
        showTools: false,
        showSearch: false,
        check: false,
        showView: true,
        addView: false,
        editStatus: false,
        docStatus: "",
        userRoles: [],
        url: "",
        viewUrl: "",
        editUrl: "",
        fieldInfo: [
            {"field": "no", "title": "序号"},
            {"field": "name", "title": "项目名称"},
            {"field": "introuceLevel", "title": "推荐等级"},
            {"field": "location", "title": "地址"},
            {"field": "projectFeature", "title": "项目特色"},
            {"field": "name", "remarks": "备注"},
            {"field": "createDate", "remarks": "创建时间"}
        ]
    };
    $.extend(ListView.prototype, {
        show: function () {
            this.toolsbarElement = $('<div class="toolbar blue clearfix"></div>').appendTo(this.target);
            this.containerElement = $('<div class="tb-panel box"/>').appendTo(this.target)
            if (this.setting.showTools) {
                this.drawToolsbar();
            }
            this.get();
        },
        search: function (param) {
            var self = this;
            var tmpUrl = this.url;
            if (tmpUrl.indexOf("?") != -1) {
                tmpUrl = tmpUrl + "&seq=" + Math.random();
            }
            else {
                tmpUrl = tmpUrl + "?seq=" + Math.random();
            }
            tmpUrl = tmpUrl + "&start=" + this.start + "&rowSize=" + this.rowSize;
            var requestData = param ? param : {};
            $.get(tmpUrl, requestData, function (data) {
                var queryPage = $.parseJSON(data);
                if (queryPage && queryPage.list) {
                    self.requestData = queryPage.list;
                    self.draw();
                }

            });
        },
        get: function () {
            var self = this;
            var tmpUrl = this.url;
            if (tmpUrl.indexOf("?") != -1) {
                tmpUrl = tmpUrl + "&seq=" + Math.random();
            }
            else {
                tmpUrl = tmpUrl + "?seq=" + Math.random();
            }
            tmpUrl = tmpUrl + "&start=" + this.start + "&rowSize=" + this.rowSize;
            var requestData = this.setting.param ? this.setting.param : {};
            $.get(tmpUrl, requestData, function (data) {
                var queryPage = $.parseJSON(data);
                if (queryPage && queryPage.list) {
                    self.requestData = queryPage.list;
                    self.draw();
                }

            });
        },
        getAccess: function () {
            var rtnValue = false;
            return rtnValue;
        },
        selectData: function () {
            //$(this.target)
        },
        draw: function () {
            var self = this;
            var isOpt = this.isShowOpt();
            if (self.requestData.length > 0) {
                var table = document.createElement("table");
                table.className = "table table-hover";
                var oRow = table.insertRow(table.rows.length);
                oRow.className = "tb_tr_title";
                if (self.setting.check) {
                    var oCell = oRow.insertCell(oRow.cells.length);
                    var checkItem = document.createElement("input");
                    checkItem.type = "checkbox";
                    $(checkItem).click(function (e) {
                        self.selectAll();
                    });
                    oCell.appendChild(checkItem);
                }
                for (var j = 0; j < this.fieldInfo.length; j++) {
                    var fi = this.fieldInfo[j];
                    var oCell = oRow.insertCell(oRow.cells.length);

                    oCell.innerHTML = fi.title;
                }
                if (isOpt) {
                    var oCell = oRow.insertCell(oRow.cells.length);
                    oCell.innerHTML = "";
                    oCell.style.width = "50px";
                }

                for (var i = 0; i < this.requestData.length; i++) {

                    var model = this.requestData[i];
                    var id = model.id;
                    this.addDataCache(id, model);

                    var oRow = table.insertRow(table.rows.length);
                    oRow.setAttribute("id", id);
                    $(oRow).click(function (e) {
                        e.stopPropagation();
                        var tmpId = $(this).attr("id");
                        if (self.viewUrl) {
                            var strUrl = self.dbPath + self.viewUrl + "/" + tmpId;
                            window.open(strUrl, "_blank");
                        }

                    });
                    oRow.onmouseover = this.highlightResult;
                    oRow.onmouseout = this.unhighlightResult;
                    if (self.setting.check) {
                        var oCell = oRow.insertCell(oRow.cells.length);
                        var checkItem = document.createElement("input");
                        checkItem.type = "checkbox";
                        checkItem.setAttribute("docId", id);
                        oCell.appendChild(checkItem);
                    }
                    for (var j = 0; j < this.fieldInfo.length; j++) {
                        var fi = this.fieldInfo[j];
                        var oCell = oRow.insertCell(oRow.cells.length);
                        var fieldValue = "";
                        if (fi.field == "no") {
                            fieldValue = i + 1;
                        }
                        else {
                            fieldValue = model[fi.field];
                        }
                        //如果数据为空，则返回空
                        fieldValue = fieldValue ? fieldValue : "";
                        if (fi.type) {
                            var type = this.type[fi.type];
                            switch (type) {
                                case this.type.img:
                                    if (fieldValue != null && fieldValue != "") {
                                        fieldValue = "<img src='" + staticServer + fieldValue + "' width='60' height='40'/>";
                                    } else {
                                        fieldValue = "<img src='/static/img/default.jpg' width='60' height='40'/>";
                                    }
                                    break;
                                case this.type.data:
                                    if (fieldValue != "") {
                                        var dataValue = fi.data && fi.data[fieldValue] ? fi.data[fieldValue] : "";
                                        fieldValue = dataValue;
                                    }
                                    break;
                                default:
                            }


                        }
                        oCell.innerHTML = fieldValue;
                    }
                    var btnCell = oRow.insertCell(oRow.cells.length);
                    btnCell.className = "opt-button";
                    if (self.isShowOpt()) {
                        btnCell.style.display = "block";
                    }
                    else {
                        btnCell.style.display = "none";
                    }
                    if (isOpt) {
                        btnCell.style.display = "block";
                    }
                    else {
                        btnCell.style.display = "none";
                    }

                    var showBtn = false;
                    if (self.setting.buttons) {
                        showBtn = true;
                        var buttonKeys = {};

                        $.each(self.setting.buttons, function (index, fn) {
                            var b = index;
                            if ($.isFunction(fn)) {
                                var buttonStatus = true;
                                if (self.setting.buttonLoad && $.isFunction(self.setting.buttonLoad)) {
                                    var loadFun = self.setting.buttonLoad;
                                    buttonKeys = loadFun.call(self, id);
                                    if (buttonKeys) {
                                        buttonStatus = buttonKeys[index];
                                    }
                                }

                                if (buttonStatus) {
                                    var btnItem = document.createElement("input");
                                    btnItem.value = b;
                                    btnItem.type = "button";
                                    btnItem.className = "btn btn-white btn-sm";
                                    btnItem.setAttribute("docId", id);
                                    $(btnItem).click(function (e) {
                                        var docId = $(this).attr("docId");
                                        e.stopPropagation();
                                        fn.call(self, this, docId);
                                    });

                                    btnCell.appendChild(btnItem);
                                }
                            }
                        })

                    }
                    if (self.setting.editStatus) {
                        showBtn = true;
                        var editItem = document.createElement("button");
                        editItem.innerHTML = "<i class='fa fa-pencil-square-o'></i> 编辑"
                        editItem.className = "btn btn-white btn-sm";
                        editItem.setAttribute("docId", id);
                        $(editItem).click(function (event) {
                            event.stopPropagation();
                            var docId = $(this).attr("docId");
                            var strUrl = self.dbPath + self.editUrl + "/" + docId;
                            window.open(strUrl, "_blank");
                        });
                        btnCell.appendChild(editItem);
                    }
                    if (self.setting.showView) {
                        showBtn = true;
                        var viewItem = document.createElement("button");
                        viewItem.innerHTML = "<i class='fa fa-pencil-square-o'></i>  查看";
                        viewItem.className = "btn btn-white btn-sm";
                        viewItem.setAttribute("docId", id);
                        $(viewItem).click(function (event) {
                            var docId = $(this).attr("docId");
                            var strUrl = self.dbPath + self.viewUrl + "/" + docId;
                            window.open(strUrl, "_blank");
                            event.stopPropagation();
                        });
                        btnCell.appendChild(viewItem);
                    }
                    if (self.setting.showDelete) {
                        showBtn = true;
                        var deleteItem = document.createElement("button");
                        deleteItem.innerHTML = "<i class='fa fa-trash-o'></i> 删除";
                        deleteItem.type = "button";
                        deleteItem.className = "btn btn-white btn-sm";
                        deleteItem.setAttribute("docId", id);
                        $(deleteItem).click(function (e) {
                            e.stopPropagation();
                            var docId = $(this).attr("docId");
                            self.deleteData(docId);
                        });
                        btnCell.appendChild(deleteItem);
                    }

                }
                this.drawPage();
                $(this.containerElement).html("");
                $(this.containerElement).append(table);
                if (this.toolsPageElement) {
                    $(this.containerElement).append(this.toolsPageElement);
                }

            }
            else {
                $(this.containerElement).html("");
                //$(this.target).html("");
                //$(this.target).append(self.toolsbarElement);
                //$(this.target).append("<div class='panel tb-panel'>" + self.noHtml + "</div>");
            }

        },
        drawToolsbar: function () {
            var self = this;
            var refreshDiv = $('<div class="fl"></div>').appendTo(this.toolsbarElement);
            $('<button type="button" id="loading-example-btn" class="btn btn-white btn-sm"><i class="fa fa-refresh"></i> 刷新</button>').click(function (e) {
                self.get();
            }).appendTo(refreshDiv);
            if (self.setting.showSearch) {
                var searchDiv = $('<div class="col-md-6 fl"></div>').appendTo(this.toolsbarElement);
                var searchGroupDiv = $('<div class="input-group"></div>').appendTo(searchDiv);
                this.searchInputElement = $(' <input type="text" placeholder="' + this.searchName + '" class="input-sm form-control search"> ').appendTo(searchGroupDiv);
                var searchSpan = $(' <span class="input-group-btn"></span>').appendTo(searchGroupDiv);
                $(' <button type="button" class="btn btn-white btn-sm">搜索</button>').click(function (e) {
                    var searchValue = $(self.searchInputElement).val();
                    var url = self.dbPath + self.searchUrl + "/" + encodeURIComponent(searchValue);
                    if (encodeURIComponent(searchValue) == null || encodeURIComponent(searchValue) == "") {
                        return;
                    }
                    $.get(url, function (data) {
                        var queryPage = $.parseJSON(data);
                        if (queryPage && queryPage.list) {
                            self.requestData = queryPage.list;
                            self.draw();
                        }
                    });
                }).appendTo(searchSpan);
            }
            var btnDiv = $('<div class="fr"></div>').appendTo(this.toolsbarElement);
            var barBtns = self.toolsbarButtons;
            if (barBtns) {
                $.each(barBtns, function (index, fn) {
                    $('<button class="btn btn-sm btn-success"></button>').html(index).click(function (e) {
                        fn.call(self);
                    }).appendTo(btnDiv);
                });
            }

        },
        drawPage: function () {
            var self = this;
            this.toolsPageElement = document.createElement("div");
            this.toolsPageElement.className = "toolbar";
            var preItem = document.createElement("input");
            preItem.type = "button";
            preItem.className = "btn btn-red";
            preItem.value = "上一页";
            $(preItem).click(function (event) {
                self.next(-1);
            });
            var nextItem = document.createElement("input");
            nextItem.type = "button";
            nextItem.className = "btn btn-red";
            nextItem.value = "下一页";
            $(nextItem).click(function (event) {
                self.next(1);
            });
            this.toolsPageElement.appendChild(preItem);
            this.toolsPageElement.appendChild(nextItem);

        },
        next: function (pageCount) {
            var tmpStart = this.start + pageCount * this.rowSize;
            if (tmpStart < 0) {
                alert("已经第一页");
            }
            else {
                this.start = tmpStart;
                this.get();
            }

        },
        selectAll: function () {
            $(this.containerElement).find("input[type=checkbox]").each(function (i) {
                var isCheck = $(this).attr("checked");
                $(this).attr("checked", !isCheck);
            });
        },
        selectCheckData: function () {
            var selectData = [];
            $(this.containerElement).find("[type=checkbox]").each(function (i) {
                if ($(this)[0].checked) {
                    var id = $(this).attr("docId");
                    if (id) {
                        selectData.push(id);
                    }
                }

            });
            return selectData;
        },
        setParam: function (param) {
            this.setting.param = param;
        },
        seeData: function (id) {
            var self = this;

        },
        deleteData: function (id) {
            var self = this;
            dialog({
                title: '确认消息',
                content: '是否删除?',
                width: 200,
                ok: function () {
                    var url = self.dbPath + self.deleteUrl + "/" + id;
                    $.get(url, function (text) {
                        self.get();
                    });
                },
                cancel: function () {

                }
            }).show();

        },
        addDataCache: function (key, obj) {
            this.data[key] = obj;
        },
        deleteDataCache: function (key) {
            if (this.data[key]) {
                delete this.data[key];
            }

        },
        isShowOpt: function () {
            //判断是否显示列表的操作栏
            var self = this;
            if (self.setting.editStatus || self.setting.showView || self.setting.showDelete || self.setting.buttons) {
                return true;
            }
            else {
                return false;
            }
        }
    });
    $.fn.listview = function (options) {
        var listview = new ListView(this, options);
        listview.show();
        return listview;
    };
})(jQuery);